<template>
  <!-- 已排产 -->
  <div style="width:100%;text-align:right;margin-bottom:2px"><el-button style="marginRight:10px" type="primary" :icon="Search" class="stbutencx" @click="selectHandler">查询</el-button></div>
  <div ref="tablediv" style=" box-sizing: border-box;min-height:100%;background-color: #fff;">
    <!-- <a-table style="height: 100%;" size="mini" :scrollbar="scrollbar" sticky-header stripe :bordered="true"
      :columns="columns" :loading="table.tableLoading" :data="tableCon.tableConter" :pagination="false"
      :rowKey="rowKey">
    </a-table> -->
    <AgGridVuesCopys style="height:600px;" class="ag-theme-alpine" :columnDefs="columns" :rowData="tableCon.tableConter"
      :defaultColDef="defaultColDef" rowSelection="multiple" @grid-ready="gridReady">
    </AgGridVuesCopys>
    <div class="pagings">
      <paginationCopys :total="paging.total" v-model:current='pages' show-page-size show-total show-jumper size="mini"
        @change="pagingChange" @page-size-change="pagingSizeChange" />
    </div>
    <div class="ypcpx">
      <div class="ypcpx-ks" v-for="item in object.sbbhoarr" :key="item.i">
        <div class="ypcpx-title">
          <span>{{ item.machineCode }}</span>
        </div>
        <div class="ypcpx-conte" v-for="items in item.dataList" :key="items.id">
          <div>
            <span>流程卡: </span>
            <span>{{ items.flowCardCode }}</span>
          </div>
          <div>
            <span>颜色: </span>
            <span>{{ items.colorCode }}</span>
          </div>
          <div>
            <span>客户: </span>
            <span>{{ items.customName }}</span>
          </div>
          <div>
            <span>急单类型: </span>
            <span>{{ items.anxiousOrderType }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { post, get } from "@/api/http";
import {
  useTable,
  useRowKey,
  useTableColumn,
  usePagination,
  useRowSelection,
} from "@/hooks/table";

import { ref, reactive, onMounted, onActivated, onUnmounted } from "vue";
import Toolbar from "@/components/Toolbar.vue";
import { Form, Message, Modal, Pagination } from "@arco-design/web-vue";
import { FormInstance } from "@arco-design/web-vue/es/form";
import emitter from "@/hooks/useEventBus";
import validate from "@/hooks/useValidate";
//import { baseURL } from '../../../api/axios.config'
import axios from "axios";
import filedownload from 'js-file-download'
import "ag-grid-community/styles/ag-grid.css";
import "ag-grid-community/styles/ag-theme-alpine.css";
import {  } from "ag-grid-vue3";
interface ClothSet {
  id: any;
  serialNumber: number | undefined,
  mercery: string | undefined;
  deleteState: any
  remark: string | undefined;
  createName: string | undefined;
  createTime: string | undefined;
  updateName: string | undefined;
  updateTime: string | undefined;
}
interface pagings {
  size: number | string,
  total: number | string,
}
export default {
  name: "productionModedp",
  setup() {
    //  const headerShow = ref<boolean>(true)
    //查询
    const scrollbar = ref(true)
    const pages = ref(1);
    const paging: pagings = reactive({
      size: 10,
      total: 30,
    })
    const object = reactive({
      sbbhoarr: []
    })
    function doRefresh() {

      pageData.pageLoading = true

      post({
        url: "/aps/schedulOrder/getPage",
        data: {
          page: pages.value,
          limit: paging.size,
          flowCardCode: "",
          colorCode: "",
          workshop: "",
          customName: "",
          merchandiser: "",
          greyCode: "",
          auditState: 0,
          startDate: "",
          endDate: "",
          schedulState: 2
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {

            tableCon.tableConter = data.list;
            paging.total = data.total;

          }
        })
        .catch(console.log).finally(() => {
          pageData.pageLoading = false
        })
    }
    function doRefreshs() {
      post({
        url: "/aps/schedulOrder/getInfo",
        data: {
          schedulState: 2
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            // console.log(data,"结果");
            object.sbbhoarr = data
            console.log(object.sbbhoarr, "已排产结果33333333333333");
          }
        })
        .catch(console.log).finally(() => {

        })
    }

    const { selectedRowKeys, onSelectionChange } = useRowSelection();
    const pagination = usePagination(doRefresh);
    const table = useTable();
    const rowKey = useRowKey("id");
    //检验表单是否含有中文的方法
    const hasChiese = validate.includeChinese;
    // const columns = [
    //   {
    //     title: '设备编号',
    //     key: "controlMachineCode",
    //     width: 150,
    //     align: "center",
    //     dataIndex: 'controlMachineCode',
    //   },
    //   {
    //     title: '缸型',
    //     key: "cylinderType",
    //     width: 150,
    //     dataIndex: 'cylinderType',
    //     align: "center"
    //   },
    //   {
    //     title: '管型',
    //     key: "tubeType",
    //     width: 150,
    //     dataIndex: 'tubeType',
    //     align: "center"
    //   },
    //   {
    //     title: '流转卡号',
    //     key: "flowCardCode",
    //     width: 150,
    //     dataIndex: 'flowCardCode',
    //     align: "center"
    //   },
    //   {
    //     title: '布号',
    //     key: "greyCode",
    //     width: 150,
    //     dataIndex: 'greyCode',
    //     align: "center"
    //   },
    //   {
    //     title: '品名',
    //     key: "productName",
    //     width: 150,
    //     dataIndex: 'productName',
    //     align: "center"
    //   },
    //   {
    //     title: '颜色深浅',
    //     key: "colorDepth",
    //     width: 150,
    //     dataIndex: 'colorDepth',
    //     align: "center"
    //   },
    //   {
    //     title: '匹数',
    //     key: "houseNum",
    //     width: 150,
    //     dataIndex: 'houseNum',
    //     align: "center"
    //   },
    //   {
    //     title: '重量',
    //     key: "flowCardWeight",
    //     width: 150,
    //     dataIndex: 'flowCardWeight',
    //     align: "center"
    //   },
    //   {
    //     title: '单位',
    //     key: "unit",
    //     width: 150,
    //     dataIndex: 'unit',
    //     align: "center"
    //   },
    //   {
    //     title: '订单号',
    //     key: "planOrderCode",
    //     width: 150,
    //     dataIndex: 'planOrderCode',
    //     align: "center"
    //   },
    //   {
    //     title: '客户名称',
    //     key: "customName",
    //     width: 150,
    //     dataIndex: 'customName',
    //     align: "center"
    //   },
    //   {
    //     title: '订单交期',
    //     key: "orderDate",
    //     width: 150,
    //     dataIndex: 'orderDate',
    //     align: "center"
    //   },
    //   {
    //     title: '订单条数',
    //     key: "orderStripNum",
    //     width: 150,
    //     dataIndex: 'orderStripNum',
    //     align: "center"
    //   },
    //   {
    //     title: '订单重量',
    //     key: "orderWeight",
    //     width: 150,
    //     dataIndex: 'orderWeight',
    //     align: "center"
    //   },
    //   {
    //     title: '染色类型',
    //     key: "dyeingType",
    //     width: 150,
    //     dataIndex: 'dyeingType',
    //     align: "center"
    //   },
    //   {
    //     title: '车间',
    //     key: "workshop",
    //     width: 150,
    //     dataIndex: 'workshop',
    //     align: "center"
    //   },
    //   {
    //     title: '开始时间',
    //     key: "address",
    //     width: 150,
    //     dataIndex: 'address',
    //     align: "center"
    //   },
    //   {
    //     title: '生产交期',
    //     key: "productionDate",
    //     width: 150,
    //     dataIndex: 'productionDate',
    //     align: "center"
    //   },
    //   {
    //     title: '建立人',
    //     key: "createName",
    //     width: 150,
    //     dataIndex: 'createName',
    //     align: "center"
    //   },
    //   {
    //     title: '建立时间',
    //     key: "createTime",
    //     width: 150,
    //     dataIndex: 'createTime',
    //     align: "center"
    //   },
    //   {
    //     title: '修改人',
    //     key: "updateName",
    //     width: 150,
    //     dataIndex: 'updateName',
    //     align: "center"
    //   },
    //   {
    //     title: '修改时间',
    //     key: "updateTime",
    //     width: 150,
    //     dataIndex: 'updateTime',
    //     align: "center"
    //   },
    // ];
    /************************************** */
    const columns = [
      // {
      //   headerName: '',//选择列头部显示的文字，可以为空
      //   checkboxSelection: true,//设置为ture显示为复选框
      //   headerCheckboxSelection: true, //表头是否也显示复选框，全选反选用
      //   pinned: 'left', //固定再左边
      //   width: 50 //列的宽度
      // },
      { headerName: "设备编号", field: "controlMachineCode",width: 100 },
      { headerName: "缸型", field: "cylinderType", width: 100 },
      { headerName: "管型", field: "tubeType", width: 100 },
      { headerName: "流转卡号", field: "flowCardCode" , width: 100},
      { headerName: "布号", field: "greyCode" , width: 100},
      { headerName: "品名", field: "productName", width: 100 },
      { headerName: "颜色深浅", field: "colorDepth", width: 100 },
      { headerName: "匹数", field: "houseNum", width: 100 },
      { headerName: "重量", field: "flowCardWeight" , width: 100},
      { headerName: "单位", field: "unit" , width: 100},
      { headerName: "订单号", field: "planOrderCode" , width: 100},
      { headerName: "客户名称", field: "customName" , width: 100},
      { headerName: "订单交期", field: "orderDate" , width: 100},
      { headerName: "订单条数", field: "orderStripNum" , width: 100},
      { headerName: "订单重量", field: "orderWeight" , width: 100},
      { headerName: "染色类型", field: "dyeingType" , width: 100},
      { headerName: "车间", field: "workshop" , width: 100},
      { headerName: "开始时间", field: "address" , width: 150},
      { headerName: "生产交期", field: "productionDate" , width: 150},
      { headerName: "建立人", field: "createName", width: 100 },
      { headerName: "建立时间", field: "createTime", width: 150 },
      { headerName: "修改人", field: "updateName", width: 100 },
      { headerName: "修改时间", field: "updateTime" , width: 150},
      // { headerName: "操作", },

    ];
    const rowData = [
      { make: "Toyota", model: "Celica", price: 35000 },
      { make: "Ford", model: "Mondeo", price: 32000 },
      { make: "Porsche", model: "Boxster", price: 72000 },
      { make: "Toyota", model: "Celica", price: 35000 },
      { make: "Ford", model: "Mondeo", price: 32000 },
      { make: "Porsche", model: "Boxster", price: 72000 },
      { make: "Toyota", model: "Celica", price: 35000 },
      { make: "Ford", model: "Mondeo", price: 32000 },
      { make: "Porsche", model: "Boxster", price: 72000 },
    ];
    const defaultColDef = {
      sortable: true,
      filter: true,
     // flex: null,
      resizable: true,
    };
    // let tc: any[] = columnDefs.map((o) => {
    //   //let obj = {}
    //   if (o.headerName === '操作') {
    //     o['resizable'] = false
    //     o['filter'] = false
    //     o['sortable'] = false
    //     o["pinned"] = "right"
    //     o["width"] = 80
    //     o['cellRenderer'] = {
    //       template: `<a-tag color="#ff7d00"  @click="a">修改</a-tag>`,
    //       setup(props: any) {
    //         const a = () => {
    //           editHandler(props.params.data)
    //         }
    //         return {
    //           a
    //         }
    //       }

    //     }
    //   }
    //   return o
    // })
    const gridOption = ref()
    const gridReady = (params: any) => {
      console.log(params, 123321);
      gridOption.value = params.api
    }
    /***************************************** */
    const tableCon = reactive({
      tableConter: []
    });
    //页改变
    const pagingChange = (current: number) => {
      // console.log(current, "分页改变");
      pages.value = current;
      doRefresh();
    }
    //页条改变
    const pagingSizeChange = (pageSize: number) => {
      //  console.log(pageSize, "条数")
      pages.value = 1;
      paging.size = pageSize;
      doRefresh();
    }
    const alone = (rowKeys, rowKey, record) => {
      // console.log(rowKeys);
      // console.log(rowKey);
      // console.log(record);
    }
    const alonell = (selected, selectedRows,) => {
      // console.log(selected);
      // console.log(selectedRows);
    }
    const scroll = {
      x: 2000,
      y: 200
    };
    const tablediv = ref(null)
    const pageData = reactive<{
      clothList: ClothSet[]
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      pageLoading: boolean,
      theight: number,
      tablediv: any,
      rHeight: number | undefined
    }>({
      clothList: [],
      showAdd: false,
      sideTitle: "新增资料",
      dropDownData: "",
      pageLoading: false,
      theight: 0,
      tablediv: null,
      rHeight: 0
    });
    //下拉框得到焦点
    const focusSel = () => {
      selCxAll({ mercery: "" })
    }
    //下拉数据
    const options = ref<any>(pageData.clothList);
    const loading = ref(false);
    const handleSearch = (value: any) => {
      if (value) {
        const ob = { mercery: value }
        loading.value = true;
        selCxAll(ob);
        options.value = pageData.clothList;
        loading.value = false;
      } else {
        options.value = []
      }
    };

    //下拉框查询
    function selCxAll(val: any) {
      post({
        url: "pdm/ClothSet/getFieldValue",
        data: val
      }).then(({ data, code }: any) => {
        if (code === 200) {
          pageData.clothList = data;
        } else {
          Message.error({
            content: "查询失败！",
            duration: 5000,
          });
        }
      });
    }

    onMounted(() => {
      doRefresh();
      doRefreshs();
    });
    //查询
    const selectHandler = () => {
      pages.value = 1;
      doRefresh();
    }
    const queryData = reactive({
      clothType: "",
    });
    const addHandler = () => {
      for (var key in dataForm) {
        if (key === "id") {
          dataForm[key] = null;
        } else if (key == 'serialNumber') {
          dataForm[key] = 0;
        }
        else {
          dataForm[key] = "";
        }

      }
      pageData.showAdd = true;
      pageData.sideTitle = "新增资料";
    };
    const dataForm = reactive<ClothSet>({
      id: null,
      serialNumber: 0,
      createTime: "",
      mercery: "",
      remark: "",
      updateTime: "",
      updateName: "",
      createName: "",
      deleteState: 0
    });
    const formRef = ref<FormInstance>();
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          if (pageData.sideTitle === "新增资料") {
            post({
              url: "pdm/ClothSet/insert",
              data: [dataForm],
            }).then((res: any) => {
              if (res.code === 200) {
                formRef.value?.resetFields();

                pageData.showAdd = false;

                Message.success({
                  content: "新增成功",
                  duration: 5000,
                });
                doRefresh();
              } else {
                Message.error({
                  content: res.message,
                  duration: 5000,
                });
              }

            });
          } else {
            post({
              url: "pdm/ClothSet/update",
              data: [dataForm],
            }).then((res: any) => {
              if (res.code === 200) {
                formRef.value?.resetFields();
                pageData.showAdd = false;

                Message.success({
                  content: "修改成功",
                  duration: 5000,
                });
                doRefresh();
              } else {
                Message.error({
                  content: res.message,
                  duration: 5000,
                });
              }

            });
          }
        }
      });
    };
    const deleteHandler = () => {
      if (selectedRowKeys.value.length === 0) {
        return;
      }
      Modal.confirm({
        title: "系统提示",
        content: "确认删除选中的数据?",
        onOk() {
          post({
            url: "pdm/ClothSet/delete",
            data: selectedRowKeys.value,
          }).then(({ code, data }: any) => {
            if (code === 200) {
              Message.success({
                content: "删除成功",
                duration: 5000,
              });

              pagination.page = 1
              doRefresh();

            } else {
              Message.error({
                content: "删除失败",
                duration: 5000,
              });
            }

          });
        },
      });
    };
    const editHandler = (record: ClothSet) => {
      for (var key in record) {
        dataForm[key] = record[key]
      }
      pageData.sideTitle = '修改资料'
      pageData.showAdd = true
    };


    //导出
    const exports = () => {
      if (selectedRowKeys.value.length === 0) {
        Message.error('请先勾选')
        return
      } else {
        //将表头拼接出来
        let head = "<th>编号</th><th>名称</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
        //拿到当前表格数据与勾选的行做筛选

        let nowRow = table.dataList.filter(function (o) {
          return selectedRowKeys.value.indexOf(o["id"]) !== -1;
        })
        let body = "";
        nowRow.forEach(function (o) {
          body += "<tr><td>" + o["merceryCode"] + "</td>";
          body += "<td>" + o["merceryName"] + "</td>";
          body += "<td>" + o["remark"] + "</td>";
          body += "<td>" + o["createName"] + "</td>";
          body += "<td>" + o["createTime"] + "</td>";
          body += "<td>" + o["updateName"] + "</td>";
          body += "<td>" + o["updateTime"] + "</td>";
          body += "</tr>";
        })
        tableToXlsx(head, '布类资料', body)
        console.log(table)
      }
    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
        <head><meta charset="UTF-8"></head>
        <body><table border="1"><tr>${head}</tr>${body}</table></body>
    </html>`;

      const a = document.createElement('a');
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
      a.download = filename;
      a.click();
      document.removeChild(a);
    }

    //模板下载
    const downloadHandler = () => {
      axios.get(baseURL + '/product/mercery/uploadMerceryModel', {
        responseType: 'blob',
        headers: {
          token: sessionStorage.getItem('USER-TOKEN-KEY')
        }
      }).then((res) => {
        if (res.status === 200) {
          filedownload(res.data, '布类资料.xlsx')
        }
      })
    }
    //导入
    const importHandler = () => {

      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！');
          return
        }
        pageData.pageLoading = true
        axios.post(baseURL + '/product/mercery/analyseMerceryModel', formData, {
          headers: {
            "Content-Type": 'multipart/form-data',
            "token": sessionStorage.getItem('USER-TOKEN-KEY')
          },
        }).then((result) => {
          if (result.data['code'] === 200) {
            Message.success('导入成功')
          } else {
            Message.error(result.data.message)
          }

        }).finally(() => {
          pageData.pageLoading = false
          doRefresh()
        })
      })
      inputEle.click()
    }
    return {
      alone,
      alonell,
      scroll,
      scrollbar,
      tablediv,
      downloadHandler,
      importHandler,
      hasChiese,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      // tableColumns,
      table,
      columns,
      tableCon,
      rowKey,
      pageData,
      queryData,
      editHandler,
      selectHandler,
      options,
      loading,
      handleSearch,
      exports,
      focusSel,
      paging,
      pagingChange,
      pagingSizeChange,
      // headerShow
      pages,
      object,
      /**************** */
      rowData,
      defaultColDef,
    //  columnDefs,
    //  tc,
      gridReady,
      gridOption
      /************************ */
    };
  },
  components: { Toolbar,},
};
</script>
<style scoped lang="less">
.pagings {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
}

.ypcpx {
  display: flex;
  margin-top: 20px;
  height: 350px;
  overflow: auto;
}

.ypcpx-ks {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #1d2129;
  margin-left: 15px;
}

.ypcpx-title {
  width: 120px;
  display: flex;
  background: #e8f7ff;
  justify-content: center;
  align-items: center;
  color: #1d2129;
}

.ypcpx-conte {
  width: 150px;
  border: 1px solid #1d2129;
  padding: 5px 5px;
  margin-top: 10px;
  font-size: 12px;
}
/********************************************** */
.stbutencx {
    background-color: #409eff;

    &:hover {
        background-color: #79bbff;
    }
}

.ag-header-cell-resize::after {
    top: 0 !important;
    height: 100% !important;
}

.ag-cell {
    border-right: 1px solid #D9DDDF !important;
}

.stbutenxz {
    background-color: #67c23a;

    &:hover {
        background-color: #b3e19d;
    }
}
/************************************************** */
</style>